import React from 'react';
import { useParams, Link } from 'react-router-dom/cjs/react-router-dom.min';
import { useState, useEffect, useContext } from 'react';
import api from './api/api';
import DescriptionCard from './DescriptionCard';
import DataContext from './context/DataContext';
import { useHistory } from 'react-router-dom/cjs/react-router-dom';
import placeholder from './assets/placeholder_240x240.png';

const Episode = () => {

  const history = useHistory();
  const { baseUrl, loginUserId } = useContext(DataContext);
  const { id } = useParams();
  const [isLoading, setIsLoading] = useState(true);
  const [podcast, setPodcast] = useState({});
  const [episode, setEpisode] = useState({});

  const handleEdit = () => {
    history.push(`/edit-episode/${id}`);
  };

  useEffect(() => {
    const fetchPodcast = async () => {
      try {
        const episodeResponse = await api.get(`/episodes/${id}`);
        const returnedEpisode = episodeResponse.data;
        returnedEpisode.coverUrl = `${baseUrl}/episodes/${id}/cover`;
        setEpisode(returnedEpisode);
        const podcastResponse = await api.get(`/podcasts/${returnedEpisode.podcast_id}`);
        const returnedPodcast = podcastResponse.data;
        setPodcast(returnedPodcast);
        setIsLoading(false);
      }
      catch (err) {
        console.log(`Error:${err.message}`);
      }
    };
    fetchPodcast();
  }, [id, baseUrl]);

  return (
    <div className='
        container
        min-h-100
        flex-fill'
    >
      <div className="container">

        <h1 className='mt-2 mb-5'>单集详情</h1>

        {!isLoading &&
          <div className="row">

            <div className="col-lg-4 col-sm d-flex justify-content-center align-items-center">
              <img src={episode.coverUrl} onError={(e) => e.target.src = placeholder} className="img-thumbnail mb-3" alt="..." />
            </div>

            <div className='col-lg-7 col-sm text-center d-flex flex-column justify-content-center align-items-end'>
              <table className="table table-bordered table-hover">
                <tbody>
                  <tr>
                    <th scope="row">单集名称</th>
                    <td>{episode.title}</td>
                  </tr>
                  <tr>
                    <th scope="row">所属专辑</th>
                    <td><Link className="text-decoration-none" to={`/podcasts/${podcast.id}`}>{podcast.title}</Link></td>
                  </tr>
                  <tr>
                    <th scope="row">创建时间</th>
                    <td>{episode.pub_date.slice(0, 16)}</td>
                  </tr>
                  <tr>
                    <th scope="row">时长</th>
                    <td>{!episode.itunes_duration ? "未知" : `${Math.floor(episode.itunes_duration / 60)}:${episode.itunes_duration % 60}`}</td>
                  </tr>
                  <tr>
                    <th scope="row">发布状态</th>
                    <td>{episode.is_complete ? "已发布" : "未发布"}</td>
                  </tr>
                </tbody>
              </table>
              {loginUserId === podcast.author_id && <button className="btn btn-sm btn-outline-primary" onClick={handleEdit}>编辑</button>}
            </div>
            {/* <p>{podcast.description}</p> */}
            <h2 className="my-3">简介</h2>
            <DescriptionCard text={episode.description} />
          </div>
        }
        <div className="my-3"></div>

      </div>

    </div >
  );
};

export default Episode;
